package com.centaline.androidsalesblog.base;

import android.content.Context;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLngBounds;
import com.centaline.androidsalesblog.iml.BaiduMarkerClick;

import java.util.ArrayList;

/**
 * Overlay基类
 * Created by guilin on 16/4/12.
 */
public abstract class BaseOverlay<T> implements BaiduMap.OnMarkerClickListener {

    protected final Context context;
    protected final BaiduMap baiduMap;
    protected final ArrayList<T> data;
    protected final BaiduMarkerClick baiduMarkerClick;

    protected ArrayList<Overlay> overlayList;

    public BaseOverlay(Context context, BaiduMap baiduMap, ArrayList<T> data, BaiduMarkerClick baiduMarkerClick) {
        this.context = context;
        this.baiduMap = baiduMap;
        this.data = data;
        this.baiduMarkerClick = baiduMarkerClick;
        overlayList = new ArrayList<>();
        initView();
    }

    protected void initView() {
    }


    /**
     * 添加数据到map
     *
     * @param zoomToSpan 是否全部显示在视野范围内
     */
    public void addToMap(boolean zoomToSpan) {
        /*检查显示条件*/
        if (checkAll())
            return;
        removeFromMap();
        for (T t : data) {
            overlayList.add(baiduMap.addOverlay(getMarkerOptions(t)));
        }
        /*全部显示在视野范围内*/
        if (zoomToSpan)
            zoomToSpan();
    }

    /**
     * 地图状态变更
     */
    public abstract void mapStatusChange();

    /**
     * 移除所有Overlay
     */
    public void removeFromMap() {
        for (Overlay overlay : overlayList) {
            overlay.remove();
        }
        overlayList.clear();
    }

    /**
     * 获取OverlayOptions
     */
    protected abstract OverlayOptions getMarkerOptions(T t);

    /**
     * 是否在范围内部
     */
    protected abstract boolean isInBound(T t);

    /**
     * 缩放地图，使所有Overlay都在合适的视野内
     */
    protected void zoomToSpan() {
        if (checkBaiduMap()) {
            return;
        }
        if (overlayList.size() > 0) {
            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            for (Overlay overlay : overlayList) {
                if (overlay instanceof Marker) {
                    builder.include(((Marker) overlay).getPosition());
                }
            }
            baiduMap.animateMapStatus(MapStatusUpdateFactory
                    .newLatLngBounds(builder.build()));
        }
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        return overlayList.contains(marker) &&
                baiduMarkerClick.onMarkerClick(marker);
    }

    /**
     * 检查所有条件
     */
    protected boolean checkAll() {
        return baiduMap == null || data == null;
    }

    /**
     * 检查BaiduMap是否为null
     */
    protected boolean checkBaiduMap() {
        return baiduMap == null;
    }
}
